package org.sample.net.udp;

import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class UDPClient {

    private Scanner scanner;

    private DatagramSocket socket;

    private InetAddress targetAddress;

    private Integer targetPort;

    public UDPClient(InetAddress targetAddress, Integer targetPort, Integer listenPort) throws Exception {
        this.scanner = new Scanner(System.in);
        this.targetAddress = targetAddress;
        this.targetPort = targetPort;
        try {
            this.socket = new DatagramSocket(listenPort);
        } catch (BindException e) {
            this.socket = new DatagramSocket(listenPort + 1);
        }
    }

    public void read() throws Exception {
        byte[] buff = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buff, buff.length);
        while (true) {
            this.socket.receive(packet);
            this.targetAddress = packet.getAddress();
            this.targetPort = packet.getPort();
            System.out.println(new String(buff));
        }
    }

    public void write() throws Exception {
        DatagramPacket packet;
        while (scanner.hasNext()) {
            String msg = scanner.nextLine() + "\n";
            byte[] bytes = msg.getBytes();

            packet = new DatagramPacket(bytes, bytes.length, targetAddress, targetPort);
            socket.send(packet);
        }
    }

    public void close() {
        scanner.close();
        socket.close();
    }

}